<template>
  <div>
    <a-alert style="text-align: center;margin-bottom: 10px" message="所有文件只保留5分钟，5分钟后将自动删除！" type="info"/>

    <a-form>
      <a-row>
        <a-col :span="24">
          <a-form-item label="修改尺寸" :label-col="{span: 2}" :wrapper-col="{span: 22}">
            <span style="margin-left: 20px">宽：</span>
            <a-input-number v-model="wideValue" :min="1" :max="9999" style="margin-right: 30px"/>
            <span>高：</span>
            <a-input-number v-model="highValue" :min="1" :max="9999"/>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <el-upload
      class="upload-demo"
      drag
      action=""
      multiple
      :show-file-list="false"
      :limit="limit"
      :before-upload="beforeAvatarUpload"
      :http-request="uploadResourceRequest"
      :on-exceed="handleExceed"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip">支持单个或批量上传。一次最多修改20张！</div>
    </el-upload>
    <a-button style="width: 45%;margin: 0 3.3% " v-if="resultList.length != 0" @click="clearResultList">
      全部清空
    </a-button>
    <a-button style="width: 45%" v-if="resultList.length != 0" @click="downloadAll">
      一键下载
    </a-button>
    <ul class="joe_detail__friends" style="grid-template-columns: repeat(5, 1fr);">
      <template v-for="item in resultList">
        <li class="joe_detail__friends-item">
          <div>
            <img width="100%" height="100%"
                 style="margin-top: 20px"
                 :src="getImgView(item.filePath)"
            >
            <div style="margin-top: 20px;text-align: center">
              <p>{{ item.orgName }} </p>
              <p>{{ item.orgImg }}</p>
              <p>{{ item.newImg }}</p>
              <a-button>
                <a :href="getDownloadUrl( item.filePath)">
                  下载
                </a>
              </a-button>

            </div>
          </div>
        </li>
      </template>
    </ul>


  </div>
</template>


<script>
import {getAction, getFileAccessHttpUrl, postAction} from '@/api/manage'
import AntsImageUpload from '@/components/ants/AntsImageUpload'

export default {
  name: 'imgResize',
  components: {
    AntsImageUpload
  },
  data() {
    return {
      url: {
        compressUpload: '/articleView/imgResize',
        clearFile: '/articleView/clearFile',
        downloadImg: process.env.VUE_APP_BASE_API + 'sys/common/static/'
      },
      bizPath: 'imgResize',
      wideValue: 800,
      highValue: 800,
      resultList: [],
      limit: 20
    }
  },
  created() {
  },
  methods: {
    key() {
      return this.$route.path
    },
    /* 图片预览 */
    getImgView(text) {
      if (text && text.indexOf(',') > 0) {
        text = text.substring(0, text.indexOf(','))
      }
      return getFileAccessHttpUrl(text)
    },
    getDownloadUrl(url) {
      return this.url.downloadImg + url;
    },
    beforeAvatarUpload(file) {
      let fileType = file.type
      if (fileType.indexOf('image') < 0) {
        this.$message.error('只能上传图片！');
        return false
      }
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isLt2M;
    },
    /**
     * 自定义上传
     * @param elementUI自动传的参数，这个参数就是文件对象
     * */
    uploadResourceRequest(param) {
      param.status = 'uploading';    //文件上传状态
      param.percentage = 0;    //文件上传进度，这里设为0
      param.name = param.file.name    //文件名

      const formData = new FormData();
      formData.append('size', param.file.size)
      formData.append('file', param.file)
      formData.append("biz", this.bizPath);
      formData.append("width", this.wideValue);
      formData.append("height", this.highValue);
      postAction(this.url.compressUpload, formData).then(res => {
        if (res.success) {
          this.resultList.push(res.result)
          param.status = 'success';  //上传成功后将status属性改成success
        } else {
          param.status = 'failed';
          param.message = '上传失败';
        }
      });
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 ` + this.limit + ` 个文件，本次选择了 ${files.length} 个文件!`);
    },
    clearResultList() {
      postAction(this.url.clearFile, this.resultList)
      this.resultList = []
    },
    downloadAll() {
      this.resultList.forEach(e => {
        // window.location.href(this.getDownloadUrl(e.filePath))
        const el = document.createElement('a');
        el.style.display = 'none';
        el.setAttribute('target', '_blank');
        /**
         * download的属性是HTML5新增的属性
         * href属性的地址必须是非跨域的地址，如果引用的是第三方的网站或者说是前后端分离的项目(调用后台的接口)，这时download就会不起作用。
         * 此时，如果是下载浏览器无法解析的文件，例如.exe,.xlsx..那么浏览器会自动下载，但是如果使用浏览器可以解析的文件，比如.txt,.png,.pdf....浏览器就会采取预览模式
         * 所以，对于.txt,.png,.pdf等的预览功能我们就可以直接不设置download属性(前提是后端响应头的Content-Type: appeam，如果为application/pdf浏览器则会判断文件为 pdf ，自lication/octet-str动执行预览的策略)
         */
        el.setAttribute('download', e.orgName);
        el.href = this.getDownloadUrl(e.filePath);
        document.body.appendChild(el);
        el.click();
        document.body.removeChild(el);
      })
    }
  }

}
</script>

<style scoped>
/deep/ .el-upload {
  width: 100%;
}

/deep/ .el-upload .el-upload-dragger {
  width: 100%;
}


</style>

